package ofpof.web.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ofpof.database.MongoDatabaseConnectionProvider;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.filter.OncePerRequestFilter;

public class MongoSessionInViewFilter extends OncePerRequestFilter {

	private MongoDatabaseConnectionProvider connectionProvider;
	
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
		initConnectionProvider();
		connectionProvider.startRequest();
		try {
			chain.doFilter(request, response);
		} finally {
			connectionProvider.stopRequest();
		}
	}
	
	public void initConnectionProvider() {
		if (connectionProvider == null) {
			WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
			connectionProvider =  (MongoDatabaseConnectionProvider) wac.getBean("mongoConnectionProvider");
		}
	}
	
	

}
